using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

//using Microsoft.SharePoint;
//using Microsoft.SharePoint.WebPartPages;

namespace SmartPart
{
    /// <summary>
    /// Description of the toolpart. Override the GetToolParts method in your WebPart
    /// class to invoke this toolpart. To establish a reference to the Web Part 
    /// the user has selected, use the ParentToolPane.SelectedWebPart property.
    /// </summary>
    public class UserControlToolpart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        string _userControlPath = null;

        internal const string INPUTID = "SmartPartControlInput";
        internal const string SELECTID = "SmartPartControlSelect";
        internal const string DEFAULTLISTITEM = "None";

        /// <summary>
        /// Constructor for the class.
        /// </summary>
        public UserControlToolpart(string userControlPath)
        {
            _userControlPath = userControlPath;
            this.Title = "User Control";
            this.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
        }

        ///	<summary>
        ///	This method is called by the ToolPane object to apply property changes to the selected Web Part. 
        ///	</summary>
        public override void ApplyChanges()
        {
            SmartPart ucc = (SmartPart)this.ParentToolPane.SelectedWebPart;

            if (Array.IndexOf(this.Page.Request.Form.AllKeys, ucc.ID + INPUTID) > -1)
            {
                //Textbox was used
                ucc.UserControl = this.Page.Request.Form[ucc.ID + INPUTID];
            }
            else
            {
                //Dropdown list was used
                if (this.Page.Request.Form[ucc.ID + SELECTID] == DEFAULTLISTITEM)
                    ucc.UserControl = null;
                else
                    ucc.UserControl = this.Page.Request.Form[ucc.ID + SELECTID];
                ucc.GetToolParts();
                ucc.RefreshPropertyValues();
            }
        }

        /// <summary>
        ///	If the ApplyChanges method succeeds, this method is called by the ToolPane object
        ///	to refresh the specified property values in the toolpart user interface.
        /// </summary>
        public override void SyncChanges()
        {
        }

        /// <summary>
        ///	This method is called by the ToolPane object if the user discards changes to the selected Web Part. 
        /// </summary>
        public override void CancelChanges()
        {
        }

        /// <summary>
        /// Render this tool part to the output parameter specified.
        /// </summary>
        /// <param name="output">The HTML writer to write out to </param>
        protected override void RenderToolPart(HtmlTextWriter output)
        {
            SmartPart ucc = (SmartPart)this.ParentToolPane.SelectedWebPart;

            if (ucc.UserControlPath == string.Empty)
            {
                #region Render textbox
                output.Write("User control to display:<br>");
                output.Write("<input name='{0}' STYLE='width: 100%' value='{1}'>", ucc.ID + INPUTID, ucc.UserControl);
                #endregion
            }
            else
            {
                #region Render dropdownlist
                string selectedUserControl = null;

                //--- MVK 
                //MapPathSecure requires ASP.NET permission set to have IO read that is why
                //we had issue running under Minimal
                //string physicalPath = this.MapPathSecure(_userControlPath);
                string physicalPath = Page.Request.MapPath(_userControlPath);
                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(physicalPath);
                }
                catch (Exception ex)
                {
                    output.Write("Could not open user control path: {0}", ex.ToString());
                    return;
                }


                output.Write("User control to display:<br>");
                output.Write("<select name='{0}' STYLE='width: 100%'>", ucc.ID + SELECTID);
                output.Write("<option value='{0}'>{0}", DEFAULTLISTITEM);

                foreach (string file in files)
                {

                    if (file.EndsWith(".ascx"))
                    {
                        string fileName = file.Substring(physicalPath.Length + 1);
                        string description = null;
                        try
                        {
                            Control control = this.Page.LoadControl(@"~\" + _userControlPath + @"\" + fileName);

                            //Get description
                            object[] classAttributes = control.GetType().GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
                            if (classAttributes.Length > 0)
                                description = ((System.ComponentModel.DescriptionAttribute)classAttributes[0]).Description;
                            else
                                description = control.GetType().Name;
                            
                            if (ucc.UserControl == @"~\" + _userControlPath + @"\" + fileName)
                            {
                                output.Write("<option value='{0}' selected>{1}", @"~\" + _userControlPath + @"\" + fileName, description);
                                selectedUserControl = control.GetType().FullName;
                            }
                            else
                                output.Write("<option value='{0}'>{1}", @"~\" + _userControlPath + @"\" + fileName, description);
                        }
                        catch
                        {
                            output.Write("<option value='{0}'>{1}", @"~\" + _userControlPath + @"\" + fileName, "Could not load " + fileName);
                        }
                        
                    }
                }

                output.Write("</select>");
                #endregion
            }
        }
    }
}

